package com.chalk.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
//import com.chalk.model.Withdrawal;
import com.chalk.service.AlipayService;
import com.chalk.util.alipay.AlipayConfig;
import com.chalk.vo.AliPayVo;
import com.chalk.vo.Refund;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建支付订单
 */
@Service
public class AlipayServiceImpl implements AlipayService {


    //创建支付订单
    @Override
    public  Map<String, String> aliPay(AliPayVo aliPayVo) {
        Map<String,String> success = new HashMap<>();

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        //实例化客户端
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(aliPayVo.getBody());
        model.setSubject(aliPayVo.getSubject());
        model.setOutTradeNo(aliPayVo.getOutTradeNo());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(aliPayVo.getTotalAmount());
        model.setProductCode(AlipayConfig.QUICK_MSECURITY_PAY);
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            request.setNotifyUrl(AlipayConfig.notify_url);

            //System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。

            String orderString = response.getBody();

            success.put("success", orderString);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return success;
    }

    @Override
    public String transactionFind(String outTradeNo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY,"json","GBK", AlipayConfig.ALIPAY_PUBLIC_KEY,"RSA2");

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        String biz="{" +
                "\"out_trade_no\":\"" +outTradeNo+ "\"" +
                "  }";
        request.setBizContent(biz);
        System.out.println(biz);


        AlipayTradeQueryResponse response = alipayClient.execute(request);

        String orderString = response.getBody();

        JSONObject jsonObject = JSONObject.fromObject(orderString);
        String code = jsonObject.getJSONObject("alipay_trade_query_response").getString("code");

        //JSONArray jsonArray = JSONArray.fromObject(jsonObject);

       // List<PayResult> payResults=jsonArray;


        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return code;
    }

    @Override
    public List<Refund> refund(AliPayVo aliPayVo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE); //获得初始化的AlipayClient
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类

        String sno="SN"+System.currentTimeMillis();

        request.setBizContent("{" +
                "\"out_trade_no\":\"" +aliPayVo.getOutTradeNo()+ "\"," +
                "\"out_request_no\":\"" +sno+ "\"," +
                "\"refund_amount\":\"" +aliPayVo.getTotalAmount()+
                "\"}"); //设置业务参数
        AlipayTradeRefundResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
        System.out.print(response.getBody());

        //根据response中的结果继续业务逻辑处理

        String orderString = response.getBody();

        JSONObject jsonObject = JSONObject.fromObject(orderString);
        jsonObject = jsonObject.getJSONObject("alipay_trade_refund_response");
        JSONArray jsonArray = JSONArray.fromObject(jsonObject);

        List<Refund> payResults=jsonArray;

        return payResults;
    }


//    @Override
//    public String transfer(Withdrawal withdrawal)throws  AlipayApiException{
//        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
//                AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
//                AlipayConfig.SIGNTYPE); //获得初始化的AlipayClient
//        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
//        request.setBizContent("{" +
//                "\"out_biz_no\":\""+withdrawal.getWithdrawalNo()+"\"," +
//                "\"trans_amount\":"+withdrawal.getMoney()+"," +
//                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
//                "\"order_title\":\""+withdrawal.getRealName()+"提现\"," +
//                "\"payee_info\":{" +
//                "\"identity\":\""+withdrawal.getAliPayAmount()+"\"," +
//                "\"identity_type\":\"ALIPAY_LOGON_ID\"," +
//                "\"name\":\""+withdrawal.getRealName()+"\"" +
//                "    }," +
//                "\"remark\":\"单笔转账\"," +
//                "  }");
//        AlipayFundTransUniTransferResponse response = alipayClient.execute(request);
//
//        String orderString = response.getBody();
//        JSONObject jsonObject = JSONObject.fromObject(orderString);
//        String code = jsonObject.getJSONObject("alipay_trade_query_response").getString("code");
//
//        if(response.isSuccess()){
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//        }
//        return code;
//    }
}
